<?php
namespace App\Logic\MonthlyReportLT\ParseTmp;

use App\Models\MonthlyReportLT\Payment\PaymentOrder;
use App\Models\MonthlyReportLT\Payment\PaymentSales;
use App\Models\MonthlyReportLT\Payment\PaymentServiceFee;
use App\Models\MonthlyReportLT\Tmp\TmpServiceFee;

class ParseServiceFee
{
    public static function exeParse($date){
        $totalQuantity = PaymentOrder::query()->where('report_date',$date)->sum('quantity');
        $totalServiceFee = TmpServiceFee::query()->where('report_date',$date)->pluck('fee','type')->toArray();
        PaymentSales::query()
            ->where('report_date',$date)
            ->orderBy('id')
            ->chunk(100, function ($lines) use ($totalQuantity,$totalServiceFee) {
                foreach ($lines as $line){
                    $item = [];
                    foreach ($totalServiceFee as $feeType => $fee){
                        $item[$feeType] = round($fee * $line->quantity / $totalQuantity,3);
                    }
                    PaymentServiceFee::query()->updateOrCreate(['report_date' => $line->report_date,
                        'psku_id' => $line->psku_id],
                        $item);
                }
            });
    }
}
